package com.example.pt.service;

import com.example.pt.entity.UserES;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserESSearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 按username搜索用户（排除status=1的记录）
     */
    public List<UserES> searchByUsername(String info) {
        Query query = buildUsernameQuery(info);
        SearchHits<UserES> searchHits = elasticsearchTemplate.search(query, UserES.class);
        return searchHits.stream()
                .map(SearchHit::getContent)
                .collect(Collectors.toList());
    }

    /**
     * 构建username搜索查询（排除status=1的记录）
     */
    private Query buildUsernameQuery(String info) {
        // 修改点：排除status=1的记录
        Criteria mainCriteria = new Criteria("status").not().is(1); // 排除status=1的用户

        if (StringUtils.hasText(info)) {
            // 搜索条件保持不变
            Criteria exactMatch = new Criteria("username.keyword").is(info).boost(3.0f);
            Criteria fuzzyMatch = new Criteria("username").fuzzy(info).boost(1.5f);
            Criteria partialMatch = new Criteria("username").contains(info).boost(1.0f);

            Criteria combinedCriteria = Criteria.or()
                    .subCriteria(exactMatch)
                    .subCriteria(fuzzyMatch)
                    .subCriteria(partialMatch);

            mainCriteria = mainCriteria.subCriteria(combinedCriteria);
        }

        return new CriteriaQuery(mainCriteria)
                .addSort(Sort.by(
                        Sort.Order.desc("_score")
                        //Sort.Order.desc("uid")
                ));
    }
}